package com.hp.beanstalk;

import com.dinstone.beanstalkc.*;

public class Test {

    public static void main(String[] args) {
        // set beanstalkd service host and port and other connetion config,
        // then create job producer or consumer by this config.
        Configuration config = new Configuration();
        config.setServiceHost("192.168.100.41");
        config.setServicePort(11300);
        config.setConnectTimeout(2000);
        config.setReadTimeout(3000);
        BeanstalkClientFactory factory = new BeanstalkClientFactory(config);

        // create an producer instance
        JobProducer producer = factory.createJobProducer("pc_tube");

        /**
         * 四个入参分别是
         *  优先级：越小越优先
         *  延迟时间：过了该时间，消息状态被置为ready状态，可以消费
         *  消费者处理超时时间：如果消费者不能在这个时间内消费完且删除掉，该消息会重新置为ready状态，可以消费
         *  消息内容
         */
        // publish delay job to beanstalkd
        producer.putJob(1, 1, 5000, "dddd".getBytes());

        // create an consumer instance
        JobConsumer consumer = factory.createJobConsumer("pc_tube");

        // peek delay job from beanstalkd
        //入参为阻塞时间，5秒内取不到消息则job为空
        Job job = consumer.reserveJob(5);

        // do someting
        System.out.println("id = " + job.getId() + " ; data = " + new String(job.getData()));

        // job execute success, then delete it
        consumer.deleteJob(job.getId());

        // finnally close client and release resources
        producer.close();
        consumer.close();
    }

}
